package com.qys.livesMall.navy.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.qys.livesMall.common.exception.enums.ExceptionEnum;
import com.qys.livesMall.common.message.MessageServer;
import com.qys.livesMall.common.result.R;
import com.qys.livesMall.kafka.entity.shop.ShopInterestInfo;
import com.qys.livesMall.navy.common.Constant;
import com.qys.livesMall.navy.model.dto.task.AddShopCollect;
import com.qys.livesMall.navy.model.entity.NavyTask;
import com.qys.livesMall.navy.model.entity.NavyTaskDetail;
import com.qys.livesMall.navy.service.NavyShopCollectService;
import com.qys.livesMall.navy.service.NavyTaskDetailService;
import com.qys.livesMall.navy.service.NavyTaskService;
import com.qys.livesMall.navy.task.TaskInter;
import com.qys.livesMall.navy.task.TaskProducer;
import com.qys.livesMall.shop.service.ShopRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @menu NavyShopCollectServer
 * @date 2023/07/11 14:01
 */
@Slf4j
@Service
public class NavyShopCollectServiceImpl implements NavyShopCollectService {

    @Autowired
    private MessageServer messageServer;

    @Autowired
    private NavyTaskService navyTaskService;

    @Autowired
    private NavyTaskDetailService navyTaskDetailService;

    @Autowired
    private ShopRecordService shopRecordService;

    @Autowired  @Lazy
    private TaskInter taskInter;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R buildTask(AddShopCollect param){
        if (param==null|| CollectionUtils.isEmpty(param.getUserIds())||CollectionUtils.isEmpty(param.getShopIds())){
            return messageServer.failMsg(ExceptionEnum.PARAM_IS_ERROR);
        }
        NavyTask navyTask=new NavyTask();
        navyTask.setTaskType(Constant.TaskType.SHOP_COLLECT);
        navyTask.setTaskName("收藏店铺");
        navyTask.setTaskParam(JSONObject.toJSONString(param));
        navyTask.setTaskStatus(Constant.TaskStatus.RUNNING);
        navyTask.setTaskStartTime(LocalDateTime.now());
        navyTask.setCreateDate(LocalDateTime.now());
        navyTask.setUpdDate(LocalDateTime.now());
        navyTaskService.save(navyTask);

        //创建任务明细
        List<NavyTaskDetail> detailList=new ArrayList<>();
        for(int i=0;i< param.getUserIds().size();i++){
            NavyTaskDetail detail=new NavyTaskDetail();
            detail.setTaskId(navyTask.getId());
            detail.setTaskType(navyTask.getTaskType());
            detail.setSort(i+1);
            detail.setNavyIds(JSONObject.toJSONString(Arrays.asList(param.getUserIds().get(i))));
            detail.setShopIds(JSONObject.toJSONString(param.getShopIds()));
            detail.setCreateDate(LocalDateTime.now());
            detail.setTaskStatus(Constant.TaskDetailStatus.NO_START);
            detailList.add(detail);
        }
        navyTaskDetailService.batchSave(detailList);
        try {
            for (NavyTaskDetail navyTaskDetail:detailList) {
                exc(navyTaskDetail.getId());
            }
        }catch (Exception e){
            log.info("收藏店铺出错");
        }
       return R.ok();
    }

    @Override
    @Async
    public void exc(Long taskDetailId){
        NavyTaskDetail detail = navyTaskDetailService.getById(taskDetailId);
        if (detail==null){
            return;
        }
        List<String> shopIds= JSONArray.parseArray(detail.getShopIds()).toList(String.class);
        String userId=JSONArray.parseArray(detail.getNavyIds()).get(0).toString();
        try {
            shopIds.forEach(shopId ->{
                ShopInterestInfo info=new ShopInterestInfo();
                info.setUserId(Long.valueOf(userId));
                info.setShopId(Long.valueOf(shopId));
                info.setBrowseDate(LocalDateTime.now());
                shopRecordService.interest(info);
            });
        }catch (Exception e){
            detail.setTaskStatus(Constant.TaskDetailStatus.END_FAIL);
            detail.setTaskDate(LocalDateTime.now());
            navyTaskDetailService.upById(detail);
            return;
        }

        detail.setTaskStatus(Constant.TaskDetailStatus.END_SUCCESS);
        navyTaskDetailService.upById(detail);
        //同步主任务状态
        boolean end=navyTaskService.watchTaskEnd(detail.getTaskId());
        if (end){
            return;
        }
        //获取下一个任务
        NavyTaskDetail nextDetail=navyTaskDetailService.getNextDetail(detail.getTaskId());
        if (nextDetail!=null){
            taskInter.addShopCollectTask(RandomUtil.randomInt(600,5400),nextDetail.getId());
        }
    }

}

